package com.aaa.os.service.impl;

import com.aaa.common.constant.ConstantUtil;
import com.aaa.common.entity.*;
import com.aaa.common.util.*;
import com.aaa.common.vo.ProductOrderVO;
import com.aaa.os.config.RabbitMQConfig;
import com.aaa.os.dao.ProductOrderDao;
import com.aaa.os.service.*;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.aaa.common.vo.Page;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单表(ProductOrder)表服务实现类
 *
 * @author makejava
 * @since 2025-09-22 11:31:53
 */
@Service("productOrderService")
@Log4j2
public class ProductOrderServiceImpl implements ProductOrderService {
    @Resource
    private ProductOrderDao productOrderDao;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RemoteProductService remoteProductService;
    @Resource
    private RemoteRoleService remoteRoleService;
    @Resource
    private RemoteStoreService remoteStoreService;
    @Resource
    private  RemoteUserIntegralService remoteUserIntegralService;
    @Resource
    private RemoteUserIntegralLogService remoteUserIntegralLogService;
    @Resource
    private RemoteWashCarCouponService remoteWashCarCouponService;
    @Resource
    private RabbitTemplate rabbitTemplate;


    /**
     * 积分支付处理
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result integralPay(ProductOrder saveProductOrder, Integer integralId, Integer credits, Double totalIntegral) {
        try {
            //积分充足,积分支付
            // 修改订单支付方式和状态
            ProductOrder updateOrder = new ProductOrder();
            updateOrder.setId(saveProductOrder.getId());
            //updateOrder.setPayType("1"); // 积分支付标识
            updateOrder.setStatusCode(43); // 支付成功状态
            this.update(updateOrder);
            // 查询更新后的订单信息
            ProductOrderVO updatedOrderVO = this.queryById(saveProductOrder.getId());
            // 扣除用户积分
            UserIntegral userIntegral = new UserIntegral();
            userIntegral.setIntegralId(integralId);
            userIntegral.setCredits(credits - totalIntegral.intValue());
            remoteUserIntegralService.edit(userIntegral);
            // 添加优惠券
            WashCarCoupon coupon = new WashCarCoupon();
            coupon.setUserId(saveProductOrder.getUserId());
            coupon.setCouponName(saveProductOrder.getProductName());
            coupon.setCouponMoney(totalIntegral.intValue());
            coupon.setIsUsed("0");
            coupon.setCouponId(saveProductOrder.getProductId());
            coupon.setStoreId(saveProductOrder.getStoreId());
            remoteWashCarCouponService.add(coupon);
            // 记录积分日志
            UserIntegralLog log = new UserIntegralLog();
            log.setUserId(saveProductOrder.getUserId());
            log.setStoreId(saveProductOrder.getStoreId());
            log.setExpendScore(totalIntegral.intValue());
            remoteUserIntegralLogService.add(log);

            return new Result(ResultStatus.INTEGRAL_PAY.getReturnCode(),
                    ResultStatus.INTEGRAL_PAY.getReturnMessage(),
                    updatedOrderVO);
        } catch (Exception e) {
            log.error("积分支付处理失败", e);
            throw new RuntimeException("积分支付处理失败", e);
        }
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ProductOrderVO queryById(Integer id) {
        return this.productOrderDao.queryById(id);
    }

    /**
     * 分页查询，后台显示
     * @param page 筛选条件
     * @return 查询结果
     */
    @Override
    public PageInfo queryProductAndOrder(Page<ProductOrderVO> page) {
        //分页操作  分页参数一定要进行传递
        if (page == null || page.getPageNo() == null || page.getPageNo() == 0 || page.getPageSize() == null || page.getPageSize() == 0) {
            //进行业务编写时，可以抛出自定义异常
            throw new CustomException(ResultStatus.PARAM_NOT_EMPTY.getReturnCode(),
                    ResultStatus.PARAM_NOT_EMPTY.getReturnMessage());
        }
        //开启分页
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        //获取当前用户
        Integer userId = Integer.parseInt(TokenUtil.getUserId(request));

        //获取当前用户角色
        List<String> roleKeyList = remoteRoleService.queryRoleKey(userId);
        log.info("========角色列表：{}", roleKeyList);
        //角色判断
        ProductOrderVO productOrderVO = page.getData() != null ? page.getData() : new ProductOrderVO();
        if (roleKeyList.contains("guanliyuan")){
            log.info("管理员角色，查询全部订单");
        }else if (roleKeyList.contains("laoban")){
            Store store = new Store();
            store.setUserId(userId);
            List<Store> storeList = remoteStoreService.selectMyStore(store);
            // 校验：若老板没有店铺，返回空结果
            if (storeList == null || storeList.isEmpty()) {
                log.warn("老板用户[{}]没有关联店铺", userId);
                return new PageInfo<>(new ArrayList<>()); // 返回空分页结果
            }

            // 收集所有店铺ID到storeIds
            List<Integer> storeIds = new ArrayList<>();
            for (Store s : storeList) {
                storeIds.add(s.getStoreId()); // 逐个添加店铺ID
            }
            productOrderVO.setStoreIds(storeIds); // 设置多店铺ID条件

            // 修正日志：打印实际的店铺ID列表
            log.info("老板角色[用户ID:{}]，查询店铺ID列表：{}的订单", userId, storeIds);
        }
        /*//获取查询对象
        ProductOrderVO productOrder = page.getData();
        productOrder.setUserId(Integer.parseInt(TokenUtil.getUserId(request)));*/
        return new PageInfo(productOrderDao.queryAllByLimit(productOrderVO));
    }
    /**
     * 分页查询，前端查询
     *
     * @param page 筛选条件
     * @return 查询结果
     */
    @Override
    public PageInfo queryOrder(Page<ProductOrderVO> page) {
        //分页操作  分页参数一定要进行传递
        if (page == null || page.getPageNo() == null || page.getPageNo() == 0 || page.getPageSize() == null || page.getPageSize() == 0) {
            //进行业务编写时，可以抛出自定义异常
            throw new CustomException(ResultStatus.PARAM_NOT_EMPTY.getReturnCode(),
                    ResultStatus.PARAM_NOT_EMPTY.getReturnMessage());
        }
        //分页操作  分页参数一定要进行传递
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        //获取查询对象
        ProductOrderVO productOrderVO = page.getData() != null ? page.getData() : new ProductOrderVO();
        //设置用户ID
        productOrderVO.setUserId(Integer.parseInt(TokenUtil.getUserId(request)));
        return new PageInfo(productOrderDao.queryAllByLimit(productOrderVO));
    }

    /**
     * 新增数据
     *
     * @param productOrder 实例对象
     * @return 实例对象
     */
    @Override
    public ProductOrder insert(ProductOrder productOrder) {
        productOrder.setStatusCode(11);
        this.productOrderDao.insert(productOrder);

        //创建订单后，发送订单ID到延迟队列，
        // convertAnDSend(exchange,routingKey, )
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.DELAY_EXCHANGE,
                RabbitMQConfig.DELAY_ROUTING_KEY,
                productOrder.getId());
        log.info("订单ID：{}发送到延迟队列成功", productOrder.getId());
        return productOrder;
    }


    /**
     * 修改数据
     *
     * @param productOrder 实例对象
     * @return 实例对象
     */
    /*@Override
    public ProductOrderVO update(ProductOrder productOrder) {
        this.productOrderDao.update(productOrder); // 传入订单对象
        ProductOrderVO productOrderVO = this.queryById(productOrder.getId());
        remoteProductService.updateMonthlySales(productOrderVO.getProductId());
        return productOrderVO; // 根据订单ID查询更新后的数据
    }*/
    @Override
    public ProductOrderVO update(ProductOrder productOrder) {

        // 1. 更新订单
        this.productOrderDao.update(productOrder);

        // 2. 查询更新后的订单（避免空指针）
        ProductOrderVO productOrderVO = this.queryById(productOrder.getId());
        if (productOrderVO == null) {
            throw new RuntimeException("订单更新后查询失败，订单ID：" + productOrder.getId());
        }
        return productOrderVO;
    }

    @Override
    public ProductOrderVO updateOrder(ProductOrder productOrder) {
        // 1. 更新订单
        this.productOrderDao.updateOrder(productOrder);

        // 2. 查询更新后的订单（避免空指针）
        ProductOrderVO productOrderVO = this.queryById(productOrder.getId());
        if (productOrderVO == null) {
            throw new RuntimeException("订单更新后查询失败，订单ID：" + productOrder.getId());
        }

        // 3. 仅当订单状态为【支付成功（43）】时，才更新月销量
        if (productOrder.getStatusCode() != null && (productOrder.getStatusCode() == 43 || productOrder.getStatusCode() == 41)) {
            Integer productId = productOrderVO.getProductId();
            if (productId == null) {
                throw new RuntimeException("订单未关联商品，无法更新月销量，订单ID：" + productOrder.getId());
            }
            try {
                // 调用远程服务更新月销量
                remoteProductService.updateMonthlySales(productId);
            } catch (Exception e) {
                log.error("更新商品月销量失败，商品ID：{}，订单ID：{}", productId, productOrder.getId(), e);
                throw new RuntimeException("更新商品月销量失败，请稍后重试", e);
            }
        }
        // 4. 返回更新后的订单（复用查询结果）
        return productOrderVO;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.productOrderDao.deleteById(id) > 0;
    }
}
